package com.zhuiyun.project.common.controller;


import com.zhuiyun.project.api.system.user.entity.TenantUser;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * 捕获控制层异常
 * 每个controller类必须继承该类
 * @auther zcy
 * @data 2019/10/11 10:12
 */
public class BaseController {


    /**
     * 捕获异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(Exception ex) {
        Map<String, Object> responseData = new LinkedHashMap<>();
        if (ex instanceof CommonException) {
            CommonException commonException = (CommonException) ex;
            responseData.put("errMsg", commonException.getErrMsg());
            responseData.put("errCode", commonException.getErrCode());
        } else {
            responseData.put("errMsg", ex.toString());
            responseData.put("errCode", ex.getStackTrace());
        }
        return CommonResult.error(responseData);
    }


    /**
     * 获取用户缓存信息
     */
    public TenantUser getLoginUser()
    {
        return SecurityUtils.getLoginUser();
    }


    /**
     * 获取登录名
     * @return
     */
    public String getLoginName() {
        return getLoginUser().getLoginName();
    }


    /**
     * 获取登录用户id
     */
    public Integer getUserId()
    {
        return getLoginUser().getId();
    }

    /**
     * 获取用户名
     */
    public String getUsername()
    {
        return getLoginUser().getUserName();
    }

}
